package com.micro.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.micro.common.constant.Constant;
import com.micro.common.constant.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


/**
 * @author pan.shun
 * @since 2022/7/4 17:19
 */
@Slf4j
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static AntPathMatcher antPathMatcher = new AntPathMatcher();


    /**
     * Gateway 鉴权操作
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();

        boolean notFilterPath = checkPath(path,
                "/**/register", "/**/login"
        );

        if (notFilterPath) {
            // 放行路径
            return chain.filter(exchange);
        }

        // 获取响应
        ServerHttpResponse response = exchange.getResponse();

        HttpHeaders headers = request.getHeaders();

        String token = headers.getFirst(Constant.TOKEN_CONFIG.TOKEN_KEY);

        if (!StringUtils.isEmpty(token)) {
            // 放行
            log.info("网关放行");
            return chain.filter(exchange);
        } else {
            // 拦截
            log.info("网关拦截");
            byte[] bytes = stringToByte(JSON.toJSONString(R.loginError("令牌信息为空, 请登录")));
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return response.writeWith(Flux.just(buffer));
        }
    }

    private byte[] stringToByte(String responseContent) {
        return responseContent.getBytes(StandardCharsets.UTF_8);
    }

    private boolean checkPath(String path, String... val) {
        for (String match : val) {
            if (antPathMatcher.match(match, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
